import { ref, onMounted } from "vue"
import { onBeforeRouteUpdate, useRoute } from 'vue-router';
import { getCategoryAPI } from '@/apis/category';

export function useCategory() {
    const categoryData = ref({})
    const getCategory = async (id) => {
        const res = await getCategoryAPI(id)
        categoryData.value = res.result
    }

    // 解决组件复用生命周期钩子不调用的问题
    onBeforeRouteUpdate((to) => {
        // console.log('to', to)
        getCategory(to.params.id)
    })

    // 首次调用会用到
    const route = useRoute()
    onMounted(() => {
        getCategory(route.params.id)
    })

    return {
        categoryData
    }
}